package com.movecar.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.amap.api.location.core.GeoPoint;
import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.listener.BaseLocationActivity;
import com.movecar.listview.WaterFallListView;
import com.movecar.listview.WaterFallListView.IXListViewListener;
import com.movecar.model.LocationDetailBean;
import com.movecar.model.LocationDetailBean.LocationDetail;
import com.movecar.utils.Alert;
import com.movecar.utils.HttpGetRequestAsyncTask;
import com.movecar.utils.RequestResultCallback;
import com.movecar.widget.CustomProgressDialog;

/**
 * 获取位置信息
 * 
 * @author Zhao.JQ
 * 
 */
public class ChooseMyLocationActivity extends BaseLocationActivity implements OnClickListener, RequestResultCallback,
		IXListViewListener {

	private CustomProgressDialog progressDialog = null;
	protected WaterFallListView mXList;
	String apiUrl = "http://api.dianping.com/v1/business/find_businesses_by_coordinate";
	private LocationDetailBean mLocationDetailBean;
	private List<LocationDetail> mDataList;
	private List<LocationDetail> resultList = new ArrayList<LocationDetail>();
	private DataAdapter dataAdapter;
	private int pageNo = 1;
	private boolean flgMore = false;
	private GeoPoint location;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_location_list);
		startProgressDialog();
		requestLocation();
		initView();
	}

	private void initView() {
		mXList = (WaterFallListView) findViewById(R.id.mListView);
		mXList.setPullRefreshEnable(true);
		mXList.setPullLoadEnable(true);
		mXList.setXListViewListener(this);

		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("位置");

		dataAdapter = new DataAdapter(this);
		mXList.setAdapter(dataAdapter);

	}

	@Override
	public void onLocation(final GeoPoint location, final String address) {

		super.onLocation(location, address);

		this.location = location;
		jsonData(location);

	}

	@SuppressWarnings("unchecked")
	private void jsonData(GeoPoint location) {

		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("latitude", String.valueOf(location.getLatitudeE6() / 1E6));
		paramMap.put("longitude", String.valueOf(location.getLongitudeE6() / 1E6));
		paramMap.put("limit", "10");
		paramMap.put("radius", "1000");
		paramMap.put("offset_type", "1");
		paramMap.put("out_offset_type", "1");
		paramMap.put("sort", "7");
		paramMap.put("page", String.valueOf(pageNo));
		paramMap.put("format", "json");
		new HttpGetRequestAsyncTask(ChooseMyLocationActivity.this, apiUrl).execute(paramMap);
	}

	@Override
	public void onSuccess(Object object) {

		stopProgressDialog();
		String result = (String) object;

		Gson gson = new Gson();
		try {
			mLocationDetailBean = gson.fromJson(result, LocationDetailBean.class);
		} catch (Exception e) {
			return;
		}
		if ("OK".equals(mLocationDetailBean.getStatus())) {

			mDataList = mLocationDetailBean.getBusinesses();

			if (mDataList != null) {

				if (flgMore) {
					if (mDataList.size() == 0) {
						Alert.info(this, "已经加载全部");
						if (pageNo != 2) {
							pageNo = (pageNo) - 1;
						} else {
							pageNo = 0;
						}
						resetXList();
					} else {

						resultList.clear();

						for (LocationDetail bean : mDataList) {
							resultList.add(bean);
						}
						dataAdapter.addItemLast(resultList);
						resetXList();

					}
				} else {
					resultList.clear();
					if (mDataList.size() == 0) {
						Alert.info(this, "已经加载全部");

						resetXList();
					}
					for (LocationDetail bean : mDataList) {
						resultList.add(bean);

					}
					dataAdapter.addItemTop(resultList);
					dataAdapter.notifyDataSetChanged();
					resetXList();
				}

			} else {
				Alert.error(this, "系统异常");
			}
		} else {
			Alert.error(this, "请求失败");
		}

	}

	@Override
	public void onFail(String exception) {

		stopProgressDialog();
		Alert.error(this, "与服务器连接失败，请检查网络");

	}

	protected void resetXList() {

		mXList.setRefreshTime(new SimpleDateFormat("H:mm", Locale.CHINA).format(new Date()));
		mXList.stopRefresh();
		mXList.stopLoadMore();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:
			finish();

			break;

		default:
			break;
		}

	}

	class DataAdapter extends BaseAdapter {

		private Activity activity;
		private LayoutInflater inflater;
		private ViewHolder viewHolder = null;
		private LinkedList<LocationDetail> resultList;

		DataAdapter(Activity activity) {

			inflater = LayoutInflater.from(activity);
			resultList = new LinkedList<LocationDetail>();
		}

		public void addItemLast(List<LocationDetail> datas) {
			resultList.addAll(datas);
		}

		public void addItemTop(List<LocationDetail> datas) {
			resultList.clear();
			for (LocationDetail info : datas) {
				resultList.add(info);
			}
		}

		@Override
		public int getCount() {

			return resultList.size();
		}

		@Override
		public Object getItem(int arg0) {

			return resultList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup arg2) {

			final ViewHolder viewHolder;

			if (view == null) {
				viewHolder = new ViewHolder();
				view = inflater.inflate(R.layout.my_location_list_item, null);
				viewHolder.location_name = (TextView) view.findViewById(R.id.location_name);
				viewHolder.location_address = (TextView) view.findViewById(R.id.location_address);

				view.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) view.getTag();
			}

			// 字体加粗
			TextPaint tp = viewHolder.location_name.getPaint();
			tp.setFakeBoldText(true);
			viewHolder.location_name.setText(resultList.get(position).getName());
			viewHolder.location_address.setText(resultList.get(position).getAddress());

			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.putExtra("location", resultList.get(position).getName());
					setResult(RESULT_OK, intent);
					finish();

				}
			});
			return view;
		}

		class ViewHolder {
			TextView location_name, location_address;
		}
	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	@Override
	public void onRefresh() {
		flgMore = false;
		resultList.clear();
		pageNo = 1;
		requestLocation();

	}

	@Override
	public void onLoadMore() {
		flgMore = true;
		pageNo = pageNo + 1;
		jsonData(location);
	}
}